#include <iostream>
#include <string>
#include <memory>

#include "TcpServer.hpp"
#include "Connection.hpp"
#include "Socket.hpp"
#include "Accepter.hpp"

const static int gbacklog = 8;

using namespace std;

void Usage(const string &proc)
{
    cout << "Usage : " << proc << " port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(-1);
    }

    uint16_t port = stoi(argv[1]);

    // 1. 创建listensock
    unique_ptr<Socket> listen_socket = make_unique<TcpSocket>();
    listen_socket->BuildListenSocketMethod(port, gbacklog);

    // 2. 创建tcpserver
    unique_ptr<TcpServer> srv = make_unique<TcpServer>();
    unique_ptr<Accepter> accepter = make_unique<Accepter>();
    auto listen_reader = bind(&Accepter::AccepterConnection,accepter.get(),placeholders::_1);

    // 3. 构建listen对应的connection，添加到tcpserver中
    Connection *listen_connection = ConnectionFactory::BuildListenConnection(listen_socket->GetSockFd(), EPOLLIN | EPOLLET, listen_reader,srv.get());
    srv->AddConnection(listen_connection);

    // 4. 开始事件派发
    srv->Dispatcher();

    return 0;
}